package bx.job;

import akka.actor.typed.ActorRef;
import akka.actor.typed.ActorSystem;
import akka.actor.typed.Behavior;
import akka.actor.typed.Terminated;
import akka.actor.typed.javadsl.Behaviors;
import bx.job.actors.JobScheduleActor;
import bx.job.entity.BxJobInfo;
import bx.job.httpserver.AkkaJobServerServer;
import bx.job.jobstore.IJobStore;
import bx.job.jobstore.IJobWorkerStore;
import bx.job.jobstore.ITriggerStore;
import bx.job.jobstore.service.ILogStore;
import bx.job.lock.IScheduleLock;
import lombok.Getter;

import java.util.Arrays;
import java.util.List;

public class JobServerBootstrap {
    @Getter
    private static IJobStore jobStore;

    @Getter
    private static ITriggerStore triggerStore;

    @Getter
    private static IScheduleLock scheduleLock;

    @Getter
    private static IJobWorkerStore jobWorkerStore;

    @Getter
    private static ILogStore logStore;
    private static ActorSystem<Void> actorSystem;

    private static ActorRef<JobScheduleActor.JobScheduleActorMsg> jobScheduleActor;

    public static void main(String[] args) {
        bootstrap();
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(90000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            jobScheduleActor.tell(new JobScheduleActor.StopScheduleMsg());
        });
//        thread.setDaemon(true);
        thread.start();
    }

    public static void bootstrap() {
        initCoreInterface();
        initActorSystem();
    }


    private static void initActorSystem() {
        actorSystem = ActorSystem.create(JobServerBootstrap.create(), "bx-job-server-ActorSystem");
    }

    private static Behavior<Void> create() {
        return Behaviors.setup(context -> {
            AkkaJobServerServer.startJobServerServer(context);  // 启动服务端 HTTP Server
            jobScheduleActor = context.spawn(JobScheduleActor.create(), "bx-job-JobScheduleActor");
            context.watch(jobScheduleActor);
            return Behaviors.receive(Void.class).onSignal(Terminated.class, sig -> Behaviors.stopped()).build();
        });
    }

    private static void initCoreInterface() {
        jobStore = (triggerId) -> {
            List<BxJobInfo> xxlJobInfoList = Arrays.asList(BxJobInfo.builder().build());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return xxlJobInfoList;
        };
    }
}
